package com.classroompie.classroompieserver.service.impl;

import com.classroompie.classroompiecommon.constant.JwtClaimsConstant;
import com.classroompie.classroompiecommon.context.BaseContext;
import com.classroompie.classroompiecommon.properties.JwtProperties;
import com.classroompie.classroompiecommon.utils.JwtUtil;
import com.classroompie.classroompiepojo.entity.CourseModel;
import com.classroompie.classroompiepojo.entity.UserCourseModel;
import com.classroompie.classroompiepojo.entity.UserModel;
import com.classroompie.classroompiepojo.request.AddUserInput;
import com.classroompie.classroompiepojo.request.UserLoginInput;
import com.classroompie.classroompiepojo.response.GetCourseVO;
import com.classroompie.classroompiepojo.response.LoginVO;
import com.classroompie.classroompieserver.mapper.CourseMapper;
import com.classroompie.classroompieserver.mapper.UserCourseMapper;
import com.classroompie.classroompieserver.mapper.UserMapper;
import com.classroompie.classroompieserver.service.CourseService;
import com.classroompie.classroompieserver.service.UserService;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.classroompie.classroompiepojo.entity.table.CourseModelTableDef.COURSE_MODEL;

/**
 * @author jiahao
 * @since 2024/6/20 周四
 */
@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    private final CourseMapper courseMapper;

    private final UserCourseMapper userCourseMapper;

    public UserServiceImpl(UserMapper userMapper, CourseMapper courseMapper, UserCourseMapper userCourseMapper) {
        this.userMapper = userMapper;
        this.courseMapper = courseMapper;
        this.userCourseMapper = userCourseMapper;
    }


    @Override
    public void addUser(AddUserInput addUserInput) {
        // 将addStudentInput转换为UserModel并插入数据库
        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(addUserInput, userModel);
        userModel.setPassword(DigestUtils.md5DigestAsHex(addUserInput.getPassword().getBytes()));
        userMapper.insert(userModel);
    }

    @Override
    public LoginVO login(UserLoginInput userLoginInput) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", userLoginInput.getAccount());
        queryWrapper.eq("password", DigestUtils.md5DigestAsHex(userLoginInput.getPassword().getBytes()));
        UserModel userModel = userMapper.selectOneByQuery(queryWrapper);
        if (userModel == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        LoginVO loginVO = new LoginVO();
        loginVO.setIdentity(userModel.getIdentity());
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, userModel.getId());
        JwtProperties jwtProperties = new JwtProperties();
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        loginVO.setToken(token);
        return loginVO;
    }

    @Override
    public void addCourse(String code) {
        CourseModel courseModel = courseMapper.selectOneByCondition(COURSE_MODEL.CODE.eq(code));
        String id = courseModel.getId();
        String currentId = BaseContext.getCurrentId();
        UserCourseModel userCourseModel = new UserCourseModel();
        userCourseModel.setCourseId(id);
        userCourseModel.setUserId(currentId);
        userCourseModel.setIdentity("学生");
        userCourseModel.setIsTop(true);
        userCourseMapper.insertSelective(userCourseModel);
    }

    @Override
    public List<GetCourseVO> getTeachCourse() {
        String currentId = BaseContext.getCurrentId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", currentId);
        queryWrapper.eq("identity", "老师");
        queryWrapper.eq("is_archived", false);
        return getCourseModels(queryWrapper);
    }

    @Override
    public List<GetCourseVO> getLearnCourse() {
        String currentId = BaseContext.getCurrentId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", currentId);
        queryWrapper.eq("identity", "学生");
        queryWrapper.eq("is_archived", false);
        return getCourseModels(queryWrapper);
    }

    @Override
    public List<GetCourseVO> getTopCourse() {
        String currentId = BaseContext.getCurrentId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", currentId);
        queryWrapper.eq("is_top", true);
        queryWrapper.eq("is_archived", false);
        return getCourseModels(queryWrapper);
    }

    @Override
    public List<GetCourseVO> getArchiveCourse() {
        String currentId = BaseContext.getCurrentId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", currentId);
        queryWrapper.eq("is_archived", true);
        return getCourseModels(queryWrapper);
    }

    private List<GetCourseVO> getCourseModels(QueryWrapper queryWrapper) {
        List<UserCourseModel> userCourseModels = userCourseMapper.selectListByQuery(queryWrapper);
        if (!userCourseModels.isEmpty()) {
            return userCourseModels.stream().map(userCourseModel -> {
                GetCourseVO getCourseVO = new GetCourseVO();
                BeanUtils.copyProperties(userCourseModel, getCourseVO);
                CourseModel courseModel = courseMapper.selectOneById(userCourseModel.getCourseId());
                getCourseVO.setId(courseModel.getId());
                BeanUtils.copyProperties(courseModel, getCourseVO);
                return getCourseVO;
            }).toList();
        }
        return List.of();
    }
}
